#!/usr/bin/python

import urwid
from urwid.widget import BoxWidget,Text, Divider,Columns, AttrWrap, Filler
from urwid.listbox import ListBox, SimpleListWalker
from urwid.canvas import CanvasCombine
import logging

class StatusTitle(BoxWidget):
	def __init__(self, title, attr):
		self.title = title
		self.w = AttrWrap(Filler(Text(title)), attr)
		super(StatusTitle, self).__init__(self)
	
	def set_title(self, text):
	    self.title = title
		self.w.get_w().body.set_text(text)
	
	def rows(self, (maxcol, maxrow)):
	    return 1
	
	def render(self, (maxcol, maxrow)):
	    canv = self.w.get_w().body.render(self, (maxcol, maxrow))
		return canv
	
class StatusLine(BoxWidget):
	"""
	status line
	"""
	def __init__(self, tag, columns):
		"""
		columns = [(colum1_width, attr), (colum2_width,attr)]
			column1 is always fixed as title, column2 is a 1 line list.
		"""
		self.line = []
		self.tag = tag
		self.column2_text = ""
		for i in range(len(colums)):
			self.line += [('fixed',columns[i][0], AttrWrap(Filler(Text("")),colums[i][1]))]
		super(StatusLine, self).__init__(self)
	def set_title(self, text):
	    self.line[0][2].get_w().
	def rows(self, (maxcol, maxrow), focus = False):
	    return 1
	
	def render(self, (maxcol, maxrow)):
	    
	
class Footer(BoxWidget):
	"""Header contains 3 lines:
		- divider
		- 2 columns on thi line
		- 2 columns on this line
	"""
	
	ignore_focus = True
	_invalidated = False		
	def __init__(self, root=None, attr=(None, None, None, None, None)):
		"""
		attr = (divider line attr, 
						line1 caption attr, line1 content attr, 
						line2 caption attr, line2 content attr)
		"""
		self.root = root
		self.attr = attr
		self.lines = []
		div = AttrWrap(Divider('-'), attr[0])
		self.lines += [div]
		line1_caption = AttrWrap(Text(""), attr[1])
		line1_content = AttrWrap(Text(""), attr[2])
		self.lines += [Columns([("fixed", 10, line1_caption), line1_content])]
		line2_caption = AttrWrap(Text(""), attr[3])
		line2_content = AttrWrap(Text(""), attr[4])
		self.lines += [Columns([("fixed", 10, line2_caption), line2_content])]
		
		
		# log
		self.logger = logging.getLogger("log")
		formatter = logging.Formatter('%(asctime)s %(levelname)s:: %(message)s')
		h = logging.FileHandler("./log")
		h.setFormatter(formatter)
		self.logger.addHandler(h)
		self.logger.setLevel(logging.INFO)
		
			
	def update_line(self, index, caption, content):
		"""
		index - line#, greater than 0
		caption - shown in the first column
		content - shown in the second column
		"""
		if index != 1 and index != 2 :
			self.logger.error("update_line: index=%d invalid!", index)
			return None
		if isinstance(content, Text):
			text = content
		elif isinstance(content, type("")):
			text = AttrWrap(Text(content), self.attr[index*2])
		self.logger.info("update line: %d, caption=%s", index, caption)
		self.lines[index] = Columns([("fixed",10, AttrWrap(Text(caption), self.attr[index*2-1])), text])
		self.lines[index]._invalidate()
			
	def selectable( self ):
		return False
		
	def rows(self, size, focus=False):
		"""
		Return the number of lines that will be rendered.
			>>> Header("hello word").rows((10,))
				1
		"""
		(maxcol,)= size
		
		return 3
	
	def render(self, size, focus=False):
		l = []
		for i in range(len(self.lines)):
			if i==0 :
				l.append((self.lines[i].render(size, focus), None, focus))
			else:
				l.append((self.lines[i].render(size, focus), i/2-1, focus))
		canv = CanvasCombine(l)
		return canv
				
			
# for test
if __name__ == "__main__":
	import urwid.raw_display
	import urwid

	def run():
		cols, rows = ui.get_cols_rows()
		
		ui.register_palette( [
			('banner', 'light green', 'dark blue', ('standout', 'underline')),
			('bg', 'black', 'dark cyan'),
			] )
		footer = Footer(attr=(None, 'banner', 'banner', 'bg','bg'))
		footer.logger.info("cols=%d,rows=%d",cols,rows)
		hdr = urwid.AttrWrap(footer, 'banner')
		fill = urwid.Filler( hdr, 'bottom' )
		
		canvas = fill.render( (cols, rows) )
		ui.draw_screen( (cols, rows), canvas )
		while not ui.get_input():
					pass
		cols, rows = ui.get_cols_rows()
		fill.get_body().update_line(2,"hello", "wolrd")
		canvas = fill.render( (cols, rows) )
		ui.draw_screen( (cols, rows), canvas )
		
		while not ui.get_input():
			pass

	ui = urwid.raw_display.Screen()
	ui.run_wrapper( run )
	
		